﻿Type.registerNamespace("VisualCron");

VisualCron.JobsObject = function () {

    VisualCron.JobsObject.initializeBase(this);

    // fields
    this._serverId = null;
    this._gridControlId = null;
    this._jobArray = [];
    this._jobFilter = '';
    this._taskFilter = '';
    this._sortField = "";
    this._sortOrder = "";

}

VisualCron.JobsObject.prototype = {

    // properties
    get_serverId: function () {
        return this._serverId;
    },

    set_serverId: function (val) {
        this._serverId = val;
    },

    get_gridControlId: function () {
        return this._gridControlId;
    },

    set_gridControlId: function (val) {
        this._gridControlId = val;
    },

    get_jobArray: function () {
        return this._jobArray;
    },

    set_jobArray: function (val) {
        this._jobArray = val;

        if (this._jobArray) {
            this.updateGrid();
        }

    },

    get_jobFilter: function () {
        return this._jobFilter;
    },

    set_jobFilter: function (val) {
        this._jobFilter = val;

        this.applyFilter();
    },

    get_taskFilter: function () {
        return this._taskFilter;
    },

    set_taskFilter: function (val) {
        this._taskFilter = val;

        this.applyTaskFilter();
    },

    // methods
    addJob: function (job) {
        this._jobArray.push(job);
        this._applySort();
    },

    removeJob: function (job) {
        var recordId = this._jobArray.findSingle(function (toTest) { return toTest.Id == job.Id; });

        if (recordId != -1) {
            this._jobArray.splice(recordId, 1);
            this._collapseNodeByIndex(recordId);
            this.updateGrid();
        }
    },

    updateJob: function (job) {
        var recordId = this._jobArray.findSingle(function (toTest) { return toTest.Id == job.Id; });

        if (recordId != -1) {
            var oldjob = this._jobArray[recordId];

            // we do this because tasks aren't supplied with new Job object recieved from server, gridcontrol to be preserved too
            this._jobArray[recordId] = job;
            this._jobArray[recordId].tasks = oldjob.tasks;
            this._jobArray[recordId].gridControlId = oldjob.gridControlId;
            this._jobArray[recordId].containerControlId = oldjob.containerControlId;

            this._applySort();
        }
    },

    updateGrid: function () {
        var jobsView = $find(this._gridControlId).get_masterTableView();

        jobsView.set_virtualItemCount(this._jobArray.length);

        jobsView.set_dataSource(this._jobArray);
        jobsView.dataBind();

        this.hideExpanders();
        this._putTaskGridsInPlaces();
        this._restoreCollapsed();
        $find(this._gridControlId).repaint();
    },

    hideExpanders: function () {
        var jobsView = $find(this._gridControlId).get_masterTableView();

        //we use row adjustment because it turned out that each child grid is considered to be an "item" too
        //so in order to call showItem() methods and so on to appropriate rows - we have to add all nested rows to the index too
        var rowAdjustment = 0;

        var dataItems = jobsView.get_dataItems();

        for (i = 0; i < dataItems.length; i++) {
            var a = jobsView._findButtonByClickScript(dataItems[i].get_element(), "_toggleExpand");
            if (a) {
                a.hidden = (dataItems[i].getDataKeyValue("TaskCount") == "0");
            }

            if (dataItems[i].get_nestedViews() != null) {
                rowAdjustment++;
            }
        }
    },

    applyFilter: function () {
        var jobsView = $find(this._gridControlId).get_masterTableView();

        //we use row adjustment because it turned out that each child grid is considered to be an "item" too
        //so in order to call showItem() methods and so on to appropriate rows - we have to add all nested rows to the index too
        var rowAdjustment = 0;

        var dataItems = jobsView.get_dataItems();

        for (i = 0; i < dataItems.length; i++) {
            if (dataItems[i].getDataKeyValue("JobName").indexOf(this._jobFilter) == -1 && this._jobFilter && this._jobFilter.length > 0) {
                jobsView.hideItem(i + rowAdjustment);
                if (dataItems[i].get_nestedViews() != null) {
                    jobsView.collapseItem(i + rowAdjustment);
                }
            }
            else {
                jobsView.showItem(i + rowAdjustment);
            }
            if (dataItems[i].get_nestedViews() != null) {
                rowAdjustment++;
            }
        }
    },

    applyTaskFilter: function () {
    },

    addTasks: function (jobId, tasks, gridControlId, forceRebind) {
        var recordId = this._jobArray.findSingle(function (toTest) { return toTest.Id == jobId; });

        if (recordId == -1) {
            // no job found for tasks - something is wrong, but we do nothing
            return;
        }

        if (gridControlId) {
            this._jobArray[recordId].gridControlId = gridControlId;
        }

        this._jobArray[recordId].tasks = tasks;

        if (tasks || forceRebind) {
            this.updateTasksGrid(recordId);
        }
    },

    addSingleTask: function (jobId, task) {
        var recordId = this._jobArray.findSingle(function (toTest) { return toTest.Id == jobId; });

        if (recordId == -1) {
            return;
        }

        if (!this._jobArray[recordId].tasks) {
            this._jobArray[recordId].tasks = [];
        }

        this._jobArray[recordId].tasks.push(task);

        this.updateTasksGrid(recordId);
    },

    removeTask: function (jobId, task) {
        var recordId = this._jobArray.findSingle(function (toTest) { return toTest.Id == jobId; });

        if (recordId == -1) {
            return;
        }

        if (this._jobArray[recordId].tasks) {
            var taskRecordId = this._jobArray[recordId].tasks.findSingle(function (toTest) { return toTest.TaskId == task.TaskId; });

            if (taskRecordId == -1) {
                return;
            }

            this._jobArray[recordId].tasks.splice(taskRecordId, 1);

            this.updateTasksGrid(recordId);
        }

    },

    updateTask: function (jobId, task) {
        var recordId = this._jobArray.findSingle(function (toTest) { return toTest.Id == jobId; });

        if (recordId == -1) {
            return;
        }

        if (this._jobArray[recordId].tasks) {
            var taskRecordId = this._jobArray[recordId].tasks.findSingle(function (toTest) { return toTest.TaskId == task.TaskId; });

            if (taskRecordId == -1) {
                return;
            }

            this._jobArray[recordId].tasks[taskRecordId] = task;

            this.updateTasksGrid(recordId);
        }

    },

    getJobIdByTaskGridId: function (taskGridId) {
        if (taskGridId == null) {
            return null;
        }
        for (var i = 0; i < this._jobArray.length; i++) {
            if (this._jobArray[i].gridControlId == taskGridId) {
                return this._jobArray[i].Id;
            }
        }

        return null;
    },

    updateTasksGrid: function (taskRecordId) {
        var tasksView = null;
        if (this._jobArray[taskRecordId].gridControlId) {
            tasksView = $find(this._jobArray[taskRecordId].gridControlId).get_masterTableView();
        }
        else {
            if (this._jobArray[taskRecordId].containerControlId) {
                tasksView = $find("tasksGrid", this._jobArray[taskRecordId].containerControlId).get_masterTableView();
            }
            else return;
        }


        tasksView.set_dataSource(this._jobArray[taskRecordId].tasks);
        tasksView.dataBind();
        tasksView.set_virtualItemCount(this._jobArray[taskRecordId].tasks.length);

    },

    sort: function (fieldName, sortOrder) {
        this._sortField = fieldName;
        this._sortOrder = sortOrder;

        this._applySort();
    },

    _collapseNodeByIndex: function (recordId) {
        var jobsView = $find(this._gridControlId).get_masterTableView();

        jobsView.collapseItem(recordId);
    },

    _applySort: function () {
        var sortExpr = "";

        //default sort values
        if (!this._sortField || !this._sortOrder) {
            this._sortField = "JobName";
            this._sortOrder = 1;
        }

        if (this._sortOrder == 1) {
            sortExpr = String.format("this._jobArray.sort(function (a, b) {{ x = a.{0}.toLowerCase ? a.{0}.toLowerCase() : a.{0}; y = b.{0}.toLowerCase ? b.{0}.toLowerCase() : b.{0}; if (x > y) return 1; if (x < y) return -1; return 0; }});", this._sortField);
        }
        else {
            sortExpr = String.format("this._jobArray.sort(function (a, b) {{ x = a.{0}.toLowerCase ? a.{0}.toLowerCase() : a.{0}; y = b.{0}.toLowerCase ? b.{0}.toLowerCase() : b.{0}; if (x < y) return 1; if (x > y) return -1; return 0; }});", this._sortField);
        }


        // need to collapse all nested grids before they are sorted and save their states (to be recovered then)
        this._collapseAll();

        eval(sortExpr);
        this.updateGrid();
    },

    // collapses all nested grids and save states to wasExpanded property of each job
    _collapseAll: function () {
        var jobsView = $find(this._gridControlId).get_masterTableView();

        var dataItems = jobsView.get_dataItems();

        for (i = 0; i < dataItems.length; i++) {
            if (dataItems[i].get_expanded() == true) {
                jobsView.collapseItem(i);
                if (this._jobArray[i]) {
                    this._jobArray[i].wasExpanded = true;
                }
            }
            else {
                if (this._jobArray[i]) {
                    this._jobArray[i].wasExpanded = false;
                }
            }
        }
    },

    // restores expanded states using wasExpanded property of job
    _restoreCollapsed: function () {
        if (!this._jobArray) {
            return;
        }

        var jobsView = $find(this._gridControlId).get_masterTableView();

        var dataItems = jobsView.get_dataItems();

        for (i = 0; i < this._jobArray.length; i++) {
            if (this._jobArray[i].wasExpanded == true) {
                jobsView.expandItem(i);
            }
        }
    },

    //  this procedure assumes that each Tasks update panel, which was populated with data
    //  contains a hidden element with value "ownerJobId:{jobId}" and it is on the third 
    //  level of hierarchy under nested view
    _putTaskGridsInPlaces: function () {
        var jobsView = $find(this._gridControlId).get_masterTableView();

        var dataItems = jobsView.get_dataItems();

        for (i = 0; i < dataItems.length; i++) {
            var dest = dataItems[i].get_element().nextSibling;
            var source = $('[value = "ownerJobId:' + dataItems[i].getDataKeyValue("Id") + '"]');
            if (source.length > 0) {
                source = source[0].parentNode.parentNode.parentNode;

                if (source != dest) {
                    $(dest).before(source);
                }
            }
        }
    }
}
VisualCron.JobsObject.registerClass('VisualCron.JobsObject', Sys.Component);

// Since this script is not loaded by System.Web.Handlers.ScriptResourceHandler
// invoke Sys.Application.notifyScriptLoaded to notify ScriptManager
// that this is the end of the script.
if (typeof (Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();